/**
 * Created with IntelliJ IDEA.
 * User: teddy zhang
 * Date: 2015-04-17
 * Time: 11:25
 */

define(function (require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    require('lib/jquery.jcrop/jquery.Jcrop.min');

    $.widget('rk.usersettingIconCtrl', {
        options: {
            selector: null,
            success:null
        },


        _create: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me._render();

        },

        _init: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

        },

        _bind: function (data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            //初始化上传控件
            var init = false;
            var rect = null, url = '', fileName = '';
            var avatar = data.picUrl.icon, avatar180 = data.picUrl.largeIcon, avatar80 = data.picUrl.smallIcon;

            var jcrop_api, boundX, boundY; // Grab some information about the preview pane
            var $preview = $('#div_thumbs'), $img180 = $('#div_thumbs div.thumb-big img'), $img50 = $('#div_thumbs div.thumb-mid img'), $img30 = $('#div_thumbs div.thumb-sml img');



            var $liAdd = $('#file_li_add').fileupload({
                //dropZone: this.$imgPopup,
                dataType: 'json',
                //pasteZone: this.$imgPopup,
                paramName: 'uploadFile',
                //limitMultiFileUploads: 1,

                limitMultiFileUploadSize: '3 MB',
                formData: function(form) {
                    var file = this.files[0];
                    return [{
                        name: 'Filename',
                        value: file.name
                    }, {
                        name: 'pageTenantId',
                        value: window.SESSION.tenantId
                    }, {
                        name: 'pageUserId',
                        value: data.user.id
                    }]
                },
                url: '/json/oa_profile-edit/pic-preview.action',

                add: function(e, data) {
                    if (e.isDefaultPrevented()) {
                        return false;
                    }
                    if (!/\.(jpg|jpeg|gif|png)$/i.test(data.files[0].name)) {
                        return false;
                    }


                    if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) {
                        data.process().done(function() {
                            data.submit();
                        });
                    }
                },
                done: function(e, data) {
                    var result = data.result;
                    if (result.status == 0) {
                        //var dataObj = JSON.parse(result);
                        var srcUrl = result.data.srcUrl;
                        fileName = data.files[0].name;
                        if (!init) {
                            init = true;

                            //初始化切图控件
                            var $img = $('#img_avatar_holder')
                            $img.Jcrop({
                                onRelease: releaseRect,
                                onChange: updatePreview,
                                onSelect: updatePreview,
                                aspectRatio: 1,
                                boxWidth: 300,
                                boxHeight: 300
                            }, function () {
                                jcrop_api = this;
                                jcrop_api.setImage(url = srcUrl, function () {
                                    var bounds = this.getBounds();
                                    boundX = bounds[0];
                                    boundY = bounds[1];


                                    jcrop_api.setSelect(getRect(boundX, boundY));
                                    $preview.find('img').attr('src', srcUrl);
                                    jcrop_api.ui.holder.css('marginTop', (300 - boundY / jcrop_api.getScaleFactor()[1]) / 2);
                                });
                            });
                        }
                        else {
                            jcrop_api.setImage(url = srcUrl, function () {
                                var bounds = this.getBounds();
                                boundX = bounds[0];
                                boundY = bounds[1];
                                jcrop_api.setSelect(getRect(boundX, boundY));
                                $preview.find('img').attr('src', srcUrl);
                                jcrop_api.ui.holder.css('marginTop', (300 - boundY / jcrop_api.getScaleFactor()[1]) / 2);
                            });
                        }
                        $(".avatar-upload li:last").show();
                    } else {
                        var $el = $('#' + data.uid);
                        $el.find('span.load').addClass('load_failure');
                    }
                }
            });

            function releaseRect() {
                rect = null;
            }

            function getRect(w, h) {
                if (w >= h) {
                    return [(w - h) / 2, 0, h, h];
                }
                else {
                    return [0, (h - w) / 2, w, w];
                }
            }

            function updatePreview(c) {
                if (parseInt(c.w) > 0) {
                    rect = c;
                    $img180.css(pos(c, 180));
                    $img50.css(pos(c, 50));
                    $img30.css(pos(c, 30));
                }
                else {
                    rect = null;
                }
            }

            function pos(c, size) {
                return {
                    width: Math.round(size * boundX / c.w) + 'px',
                    height: Math.round(size * boundY / c.h) + 'px',
                    marginLeft: '-' + Math.round(size * c.x / c.w) + 'px',
                    marginTop: '-' + Math.round(size * c.y / c.h) + 'px'
                }
            }


            //保存和取消
            $(elem).on('click', 'a[act="icon_btn_save"]', function (event) {
                event.preventDefault();
                if (!url) {
                    rk.noticeError(rk.i18n('USERSET_NEED_HEADPIC'));
                    return false;
                }
                if (!rect) {
                    rk.noticeError(rk.i18n('USERSET_NEED_HEADPIC_ZONE'));
                    return false;
                }

                var $loading = $('<div style="position: absolute; z-index: 610; top:0; left:0; background: #000;opacity: 0.6;width: 700px;height: 500px"><p style="margin:200px auto 0 auto; text-align: center; font-size:18px; color:white;">'+rk.i18n('USERSET_SAVING_IMAGE')+'</p></div>').appendTo('#edit_profile_content');
                rk.post('/json/oa_profile-edit/pic-upload.action', {
                    xcop: Math.round(rect.x),
                    ycop: Math.round(rect.y),
                    iconHeight: Math.round(rect.h),
                    iconWidth: Math.round(rect.w),
                    uploadFileName: fileName,
                    pageTenantId: SESSION.tenantId,
                    pageUserId: SESSION.user.id,
                    iconPath: url
                }, function (json) {
                    $loading.remove();
                    if (json.status == 0) {
                        rk.noticeSuccess(rk.i18n('USERSET_HEADPIC_UPLOADED'));
                        $.isFunction(opt.success) && opt.success(json.data);
                        opt.selector.trigger('click');
                    }
                    else {
                        rk.noticeError(rk.i18n('USERSET_HEADPIC_UPLOAD_FAIL'));
                    }
                });

                return false;
            });


            $(elem).on('click', 'a[act="icon_btn_cancel"]', function (event) {
                event.preventDefault();
                jcrop_api.ui.holder.css('marginTop', 0);
                jcrop_api.setImage('/static/img/upload_def.png', function () {
                    jcrop_api.disable();
                });
                $img180.attr({
                    src: avatar180,
                    style: ''
                });
                $img50.add($img30).attr({
                    src: avatar80,
                    style: ''
                });
                $("#ul_avatar_upload li:last").css("visibility", "hidden");

                return false;
            });

        },


        _render: function () {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var default_icon = '/static/img/default_face.png';

            $.postJson('/json/oa_profile-edit/icon.action').done(function (json) {
                if (json.status == 0) {
                    var data = json.data;
                    if (!data.picUrl.icon) {
                        data.picUrl.icon = default_icon;
                        data.picUrl.smallIcon = default_icon;
                        data.picUrl.largeIcon = default_icon;
                    }
                    $(elem).html(rk.templateText(require('page/tmpl/usersetting/tpl_user_setting_icon.tpl'), data));
                    me._bind(data);
                }
            }).fail(function (def, code, message) {
                def.status != 0 && rk.noticeError(rk.i18n('REQUEST_ERROR'));
            });


        }

    });

    return $;

});

